<script setup lang="ts">
import { ElMessage } from 'element-plus'
import formateDate from '@/utils/formateDate'
import { rewardDetail, rewardUpdate, rewardCreate } from '@/api/assessment';
import { BaseSuccessRespDTO, RewardDetailVO, RewardMethodChangeHistoryVO } from '@/api/assessment/types';

const props = defineProps({
  visible: {
    type: Boolean
  },
  id: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['cancel'])

const formRef = ref()

const form = ref({
  name: '',
  year: new Date().getFullYear(),
  dangerTime: [],
  rewardMethodChangeHistory: []
})

const rules = ref({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  year: [{ required: true, message: "奖励年度不能为空", trigger: "blur" }],
  dangerTime: [{ required: true, message: "奖励时间不能为空", trigger: "blur" }],
})

const { run: getDetail } = useRequest(() => rewardDetail({ id: props.id }), {
  manual: true,
  onSuccess: (res: RewardDetailVO) => {
    form.value = {
      name: res?.name as string,
      year: res?.year as number,
      dangerTime: [formateDate(res?.startTime).format('YYYY-MM-DD'), formateDate(res?.endTime).format('YYYY-MM-DD')],
      rewardMethodChangeHistory: res?.rewardMethodChangeHistory as RewardMethodChangeHistoryVO[] || [],
    }
  }
})

const { run: update, loading: updateLoading } = useRequest(() => rewardUpdate({
  id: props.id,
  name: form.value.name,
  startTime: formateDate(form.value.dangerTime[0]).format('YYYY-MM-DD 00:00:00'),
  endTime: formateDate(form.value.dangerTime[1]).format('YYYY-MM-DD 23:59:59')
}), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      ElMessage({
        message: '新增成功!',
        type: 'success',
        plain: true,
      })
      emits('cancel', true)
    }
  }
})

const { run: create, loading: addLoading } = useRequest(() => rewardCreate({
  name: form.value.name,
  startTime: formateDate(form.value.dangerTime[0]).format('YYYY-MM-DD 00:00:00'),
  endTime: formateDate(form.value.dangerTime[1]).format('YYYY-MM-DD 23:59:59')
}), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      ElMessage({
        message: '新增成功!',
        type: 'success',
        plain: true,
      })
      emits('cancel', true)
    }
  }
})

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (props.id) {
        update()
      } else {
        create()
      }
    }
  })
}

watch(() => props.visible, () => {
  if (props.visible && props.id) {
    getDetail()
  }
}, { immediate: true })

</script>

<template>
  <el-dialog v-model="props.visible" :title="props.type === 'edit' ? '编辑奖励' : props.type === 'add' ? '新增奖励' : '查看奖励'"
    width="600px" align-center @close="emits('cancel')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="名称" prop="name">
        <el-input v-if="props.type !== 'view'" v-model="form.name" placeholder="请输入" clearable :maxlength="50"
          show-word-limit />
        <div v-else>{{ form.name }}</div>
      </el-form-item>
      <el-form-item label="奖励年度" prop="year">
        <div>{{ form.year }}年度</div>
      </el-form-item>
      <el-form-item label="奖励时间" prop="dangerTime">
        <el-date-picker v-if="props.type !== 'view'" v-model="form.dangerTime" type="daterange" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable />
        <div v-else>{{ formateDate(form.dangerTime[0]).format('YYYY-MM-DD') }}~{{
          formateDate(form.dangerTime[1]).format('YYYY-MM-DD') }}</div>
      </el-form-item>
      <el-form-item v-if="props.type === 'view' && form.rewardMethodChangeHistory?.length" label="奖励办法"
        prop="rewardMethodChangeHistory">
        <div class="flex flex-col space-y-[20px]">
          <div v-for="item in form.rewardMethodChangeHistory" :key="item.rewardMethodId">
            <div class="leading-[24px] mt-[4px]">
              <div>{{ formateDate(item.startTime).format('YYYY-MM-DD') }}~{{ item.endTime ? formateDate(item.endTime).format('YYYY-MM-DD') : '至今' }}</div>
              <div>{{ item.rewardMethodName }}</div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div v-if="props.type !== 'view'" class="dialog-footer">
        <el-button @click="emits('cancel', false)">取消</el-button>
        <el-button v-loading="updateLoading || addLoading" type="primary" @click="handleSubmit">确认</el-button>
      </div>
      <div v-else class="dialog-footer">
        <el-button @click="emits('cancel', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>